package com.raincat.multimediapicker.utils;

import android.content.Context;
import android.database.Cursor;
import android.provider.MediaStore;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

/**
 * Created by Administrator on 2018/3/27 0027.
 */

public class VideoHelper extends Helper {
    // 视频列表
    private List<VideoItem> videoItemList = new ArrayList<>();
    // 单例模式
    private static VideoHelper instance;

    // 图片获取完毕回调
    public interface onVideoItemListGetListener {
        void onFinish(List<VideoItem> videoItemList);
    }

    public static VideoHelper getInstance(Context context) {
        if (instance == null) {
            instance = new VideoHelper(context.getApplicationContext());
        }
        return instance;
    }

    private VideoHelper(Context context) {
        init(context);
    }

    /**
     * 初始化
     */
    private void init(Context context) {
        if (cr == null) {
            cr = context.getContentResolver();
        }
    }

    /**
     * 获取视频集，外部调用，异步
     */
    public void getVideoItemList(final onVideoItemListGetListener b) {
        // 构造相册索引(异步)
        new Thread(new Runnable() {
            @Override
            public void run() {
                getImagesBucketListSync(b);
            }
        }).start();
    }

    /**
     * 从数据库读取视频集，同一时间只能进入一次，第二次之后直接返回数据
     */
    private synchronized void getImagesBucketListSync(final onVideoItemListGetListener b) {
        videoItemList.clear();

        String columns[] = new String[]{MediaStore.Video.Media._ID, MediaStore.Video.Media.DATA, MediaStore.Video.Media.SIZE, MediaStore.Video.Media.DATE_MODIFIED, MediaStore.Video.Media.DURATION};
        // 得到一个游标，时间从新到旧读取
        Cursor cur = cr.query(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, columns, null, null, MediaStore.Video.Media.DATE_MODIFIED + " desc");

        if (cur.moveToFirst()) {
            // 获取指定列的索引
            int videoIDIndex = cur.getColumnIndexOrThrow(MediaStore.Video.Media._ID);
            int videoPathIndex = cur.getColumnIndexOrThrow(MediaStore.Video.Media.DATA);
            int addTime = cur.getColumnIndexOrThrow(MediaStore.Video.Media.DATE_MODIFIED);
            int videoSizeIndex = cur.getColumnIndexOrThrow(MediaStore.Video.Media.SIZE);
            int videoDurationIndex = cur.getColumnIndexOrThrow(MediaStore.Video.Media.DURATION);
            do {
                String _id = cur.getString(videoIDIndex);
                String path = cur.getString(videoPathIndex);
                long bucketTime = cur.getLong(addTime);
                String size = cur.getString(videoSizeIndex);
                long duration = cur.getLong(videoDurationIndex);

                // 文件为空或者文件太小的不保存
                if (size == null || Integer.parseInt(size) <= 1024 || !fileIsExists(path)) {
                    continue;
                }


                VideoItem item = new VideoItem();
                item.videoId = _id;
                item.videoPath = path;
                item.videoAddTime = bucketTime;
                item.videoSize = Float.valueOf(size);
                item.videoSuffix = path.substring((path.lastIndexOf(".") + 1));
                item.videoDuration = millisecond2Time(duration);

                videoItemList.add(item);
            } while (cur.moveToNext());
        }
        cur.close();

        if (b != null) {
            b.onFinish(videoItemList);
        }
    }

    private String millisecond2Time(long millisecond) {
        long second = millisecond / 1000 % 60;
        long min = millisecond / 1000 / 60 % 60;
        long hour = millisecond / 1000 / 60 / 60;

        String time = String.format(Locale.getDefault(), "%02d", hour);
        time = time + ":" + String.format(Locale.getDefault(), "%02d", min);
        time = time + ":" + String.format(Locale.getDefault(), "%02d", second);
        return time;
    }
}
